import React,{useState} from "react";
import { aiSearch } from "../../api/ai";
import "./index.scss";
interface AISearchProps{}
const AISearch:React.FC<AISearchProps>=()=>{
    const [inputValue,setInputValue]=useState("");
    const [loading,setLoading]=useState(false);
    const [messages,setMessages]=useState<{role:'user' | 'assistant'; content:string}[]>([]);
    const handleInputChange=(e:React.ChangeEvent<HTMLInputElement>)=>{
        setInputValue(e.target.value);
    };
    const handleSearch=async()=>{
        if(!inputValue.trim()){
            //提示输入内容不能为空
            alert("请输入有效的问题");
            return;
        }
        setLoading(true);
        const newUserMessage={role:'user',content:inputValue};
        setMessages([...messages,newUserMessage]);
        setInputValue("");
        try{
            const response=await aiSearch(inputValue);
            if(response.code===200){
                const newAssistantMessage={
                    role:'assistant',
                    content:response.data.result
                };
                setMessages([...messages,newUserMessage,newAssistantMessage]);
            }
            else{
                const errorMessage={
                    role:'assistant',
                    content:response.message
                };
                setMessages([...messages,newUserMessage,errorMessage]);
            }
        }catch(error){
            const errorMessage={
                role:'assistant',
                content:"请求出错，请稍后再试"
            };
            setMessages([...messages,newUserMessage,errorMessage]);
        }finally{
            setLoading(false);
        }
    };
    return (
        <div className="ai-search-container">
            <div className="messages-container">
            {messages.map((message,index)=>(
                <div key={index} className={`message ${message.role==='user'?'user-message':'assistant-message'}`}>
                   {message.content}
                </div>
            ))}
            </div>
            <div className="input-container">
                <input type="text" placeholder="请输入内容" value={inputValue} onChange={handleInputChange} />
                <button onClick={handleSearch} disabled={loading}>{loading?'加载中':'搜索'}</button>
            </div>
        </div>
    )
}
export default AISearch;